package com.xwj.shiro.filter;

import com.google.code.kaptcha.Constants;
import com.xwj.config.SystemConfig;
import com.xwj.data.StaticData;
import com.xwj.entity.SysUserLog;
import com.xwj.service.Impl.SysUserLogServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by thinkjoy on 2017/7/10.
 * 表单过滤器
 */
public class CustomFromAuthenticationFilter extends FormAuthenticationFilter {

    @Autowired
    private SysUserLogServiceImpl sysUserLogService;
    @Autowired
    private SystemConfig systemConfig;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (SecurityUtils.getSubject().isAuthenticated()) {
            return true;//已经登录过
        }
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpSession session = httpServletRequest.getSession();
        String verifyCode;
        try {
            verifyCode = httpServletRequest.getParameter("code").toUpperCase();
        } catch (NullPointerException e) {
            verifyCode = null;
        }
        //判断验证码输入是否正确
        if (verifyCode != null && !verifyCode.equals(session.getAttribute(Constants.KAPTCHA_SESSION_KEY))) {
            //如果校验失败，将验证码错误的失败信息，通过shiroLoginFailure设置到request中
            httpServletRequest.setAttribute("shiroLoginFailure", "randomCodeError");
            //拒绝访问，不再校验账号和密码
            return true;
        }
        return super.onAccessDenied(request, response);
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        ServletContext context = request.getServletContext();
        context.setAttribute(StaticData.ADMIN_USER_LOGIN_ATTRIBUTE, token.getPrincipal());
        SysUserLog sysUserLog = new SysUserLog();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sysUserLog.setAccountid(token.getPrincipal().toString());
        sysUserLog.setLogindate(format.format(new Date()));
        sysUserLog.setIp(systemConfig.getIP());
        sysUserLogService.addUserLoginLog(sysUserLog);
        WebUtils.getAndClearSavedRequest(request);//清除原先跳转的页面
        WebUtils.redirectToSavedRequest(request, response, getSuccessUrl());//设定跳转到指定页面
        subject.getSession().setTimeout(-1000l);//session永不超时
        return false;
    }
}
